package com.smproject.config.interceptor;

import cn.hutool.json.JSONUtil;
import com.smproject.config.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 编写登录状态拦截器
 * @author hu.liang
 * @Date 2019/7/2 0002
 */
@Configuration
public class RedisSessionInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //无论访问的地址是不是正确的，都进行登录验证，登录成功后的访问再进行分发，404的访问自然会进入到错误控制器中
        HttpSession session = httpServletRequest.getSession();
        if(Objects.nonNull(session.getAttribute("loginUserId"))){
            try {
                String userId = "user_id_"+ Integer.parseInt(session.getAttribute("loginUserId").toString());
                String loginSessionId = redisUtil.get(userId);
                if(Objects.nonNull(loginSessionId)&&Objects.equals(loginSessionId,session.getId())){
                    return true;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        response401(httpServletResponse);
        return false;
    }

    private void response401(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try{
            Map<String,Object> resultMaps = new HashMap<>();
            resultMaps.put("status",false);
            resultMaps.put("msg","用户未登录");
            response.getWriter().print(JSONUtil.parseObj(resultMaps));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
